﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneMgr : BaseManager<SceneMgr>
{
    public CameraControll MainCameraControl;
    internal static void OnEnterMap(Cmd cmd)
    {
        if (!Client.CherkCmd(cmd, typeof(EnterMapCmd)))
            return;
        EnterMapCmd enterMapCmd = cmd as EnterMapCmd;
        Debug.Log("地图ID:" + enterMapCmd.MapID);
        reset();
        SceneMgr.GetInstance().loadScene(enterMapCmd.MapID);
    }
    //重置脚本
    private static void reset()
    {
        UIMgr.GetInstance().RemoveLayer();
        UIMgr.GetInstance().RemoveLayer(UILayer.Touch);
        RoleMgr.GetInstance().Reset();
        NpcMgr.GetInstance().Reset();
        FightUIMgr.GetInstance().Reset();
    }

    private void loadScene(int mapID)
    {
        var mapDatabase = MapTable.GetInstance()[mapID];
        if (mapDatabase == null)
        {
            Debug.LogError("未找到地图：" + mapID);
            return;
        }
    
        
        ScenesManager.GetInstance().LoadSceneAsyn(mapDatabase.SceneName, () =>
        {
            Debug.Log("加载地图"+mapDatabase.SceneName);
        });
        UIMgr.GetInstance().UIEventSystemEnable = false;
        //阻塞消息，暂时不处理
        Client.GetInstance().Pause = true;
        //loading界面UI的Top层

        var ao = SceneManager.LoadSceneAsync(mapDatabase.SceneName);
        MonoManager.GetInstance().StartCoroutine(loadEnd(ao));
        //QuickCoroutine.GetInstance().StartCoroutine(loadEnd(ao));
    }

    private IEnumerator loadEnd(AsyncOperation ao)
    {
        while (!ao.isDone)
        {
            //加载进度 ao.progress
            yield return new WaitForEndOfFrame();
        }
        Debug.Log("场景加载完毕");
        
        
        OnLeadEnd();
    }

    private void OnLeadEnd()
    {
        InitCamera();
        FightUIMgr.GetInstance().Init();
        //放开消息
        Client.GetInstance().Pause = false;
        UIMgr.GetInstance().UIEventSystemEnable = true;
    }

    private void InitCamera()
    {
        GameObject cameraObj = ResManager.GetInstance().load<GameObject>("SceneCamera");
        MainCameraControl = cameraObj.GetComponent<CameraControll>();
        
    }
}
